import os

import pandas as pd
from loguru import logger

from models.global_config import glm
from models.stock_model import StockNumber, DayInfo
from mylib.myfile import insert_line


def get_all_stock(stocks, bkd):
    stocks_low_dict = {}
    df = pd.read_csv('all.csv')
    for row in df.index:
        if stocks is not None and df.loc[row]['ts_code'] not in stocks:
            continue
        sn = StockNumber(df.loc[row])
        sn.list_date = df.loc[row]['list_date']
        if '退' in sn.name:
            continue
        if 'ST' in sn.name:
            continue
        if not str(sn.ts_code).startswith('60') \
                and not str(sn.ts_code).startswith('00'):
            continue
        res = analysis_stock(sn, bkd)
        stocks_low_dict[sn.ts_code] = res
    return stocks_low_dict


def analysis_stock(sn, bkd):
    csv_path = f'stocks/{sn.ts_code}.csv'
    df2 = pd.read_csv(csv_path)
    list10 = []
    price_low10 = []
    result_dict = {}
    for row2 in df2.index:
        if row2 > bkd + 20:
            break
        di = DayInfo(sn, df2.loc[row2])
        if len(list10) == 10:
            # print(row2, list10)
            if min(price_low10) == min(price_low10[:3]):
                result_dict[list10[0].trade_date] = (1, sn.name)
            else:
                result_dict[list10[0].trade_date] = (0, sn.name)
            list10.pop(0)
            price_low10.pop(0)
        if len(list10) < 10:
            list10.append(di)
            price_low10.append(di.low)
            continue
    return result_dict


def run(log_dir, start_date, end_date, stocks=None, indus_num=None, indus=None, bkd=0):
    if not os.path.exists(log_dir):
        os.makedirs(log_dir)
    # logger.info(f'{log_dir} start')
    if end_date == glm.get_all_trade_days(stocks[0])[0]:
        logger.warning(f'{indus} 当前数据最近日期是{end_date}，已是最新')
        return
    stocks_low_dict = get_all_stock(stocks, bkd)
    p_path = f'{log_dir}/{indus}_all_{indus_num}.csv'
    for idx, trade_date in enumerate(glm.get_all_trade_days(stocks[0])):
        all_cnt = len(stocks_low_dict.keys())
        if trade_date >= start_date:
            continue
        if end_date is not None and trade_date <= end_date:
            break
        if idx > bkd:
            break
        # logger.info(f'cal {trade_date}')
        all_down_cnt = 0
        all_down_stocks = []
        for k, v in stocks_low_dict.items():
            if trade_date not in v:
                del stocks_low_dict[k]
                break
            if v[trade_date][0]:
                all_down_cnt += 1
                all_down_stocks.append(v[trade_date][1])
        msg = f'{trade_date},{all_down_cnt},{all_cnt}, {all_down_stocks}'
        insert_line(p_path, idx, msg)
    # logger.info('生成excel运行完成')
